package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.MqOpsService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MD5;
import com.rabbitmq.client.Channel;
import io.micrometer.common.util.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * <a href="https://www.shallowrecall.top/">Recall`Blog</a></br>
 * <a href="https://github.com/ShallowRecall">GitHub</a>
 *
 * @author Recall
 * @createTime 2025/03/13 14:35
 **/
@Component
@Slf4j
public class AccountInfoListener {

    @Autowired
    private MqOpsService mqOpsService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitService rabbitService;


    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_USER_REGISTER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER, durable = "true"),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    @SneakyThrows
    public void listenUserAccountRegister(String content, Message message, Channel channel) {

        // 1.判断消息是否存在
        if (StringUtils.isEmpty(content)) {
            return; // 不用消费
        }

        // 2.处理消息
        String msgMd5 = MD5.encrypt(content);
        // 3.消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            mqOpsService.userAccountRegister(content);
            // 手动应答消息 (将消息从队列中删除掉)
            channel.basicAck(deliveryTag, false);
        } catch (GuiguException e) {
            String msgRetryKey = "msg:retry:" + msgMd5;
            Long count = redisTemplate.opsForValue().increment(msgRetryKey);
            // 三次重试
            if (count >= 3) {
                log.error("消息已经到达了重试{}次,请人工排查错误原因:{}", count, e.getMessage());
                // 不能重试
                channel.basicNack(deliveryTag, false, false);
                redisTemplate.delete(msgRetryKey);
            } else {
                log.info("消息已经重试{}次", count);
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (IOException e) {
            log.error("网络故障导致签收消息失败{}", e.getMessage());
            channel.basicNack(deliveryTag, false, false);
        }
    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_ACCOUNT_UNLOCK, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ACCOUNT, durable = "true"),
            key = MqConst.ROUTING_ACCOUNT_UNLOCK))
    @SneakyThrows   // SneakyThrows可以绕开编译时候的异常 但是真正在运行期间出现异常依然会抛出来
    public void listenUserAccountUnlock(String orderNo, Message message, Channel channel) {


        // 1.判断消息是否存在
        if (StringUtils.isEmpty(orderNo)) {
            return;  // 不用消费
        }

        // 2.消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            mqOpsService.listenUserAccountUnlock(orderNo);
            // 3.向本地消息表队列发送一条消息
            rabbitService.sendMessage(MqConst.EXCHANGE_LOCAL_MSG, MqConst.ROUTING_LOCAL_MSG, orderNo);
            // 4.手动应答消息（将消息从队列中删除掉）
            channel.basicAck(deliveryTag, false);
        } catch (GuiguException e) {
            String msgRetryKey = "msg:retry:" + orderNo;
            Long count = redisTemplate.opsForValue().increment(msgRetryKey);
            // 三次重试
            if (count >= 3) {
                log.error("消息已经到达了重试{}次，请人工排查错误原因：{}", count, e.getMessage());
                // 不能重试
                channel.basicNack(deliveryTag, false, false);
                redisTemplate.delete(msgRetryKey);
            } else {
                log.info("消息重试{}次", count);
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (Exception e) {
            log.error("签收消息时网络出现了故障，异常原因：{}", e.getMessage());
            channel.basicNack(deliveryTag, false, false);
        }
    }

    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_ACCOUNT_MINUS, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ACCOUNT, durable = "true"),
            key = MqConst.ROUTING_ACCOUNT_MINUS))
    @SneakyThrows   // SneakyThrows可以绕开编译时候的异常 但是真正在运行期间出现异常依然会抛出来
    public void listenUserAccountMinus(String orderNo, Message message, Channel channel) {


        // 1.判断消息是否存在
        if (StringUtils.isEmpty(orderNo)) {
            return;  // 不用消费
        }

        // 2.消费消息
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            mqOpsService.listenUserAccountMinus(orderNo);
            // 3.向本地消息表发送消息
            rabbitService.sendMessage(MqConst.EXCHANGE_LOCAL_MSG, MqConst.ROUTING_LOCAL_MSG, orderNo);
            // 4.手动应答消息（将消息从队列中删除掉）
            channel.basicAck(deliveryTag, false);
        } catch (GuiguException e) {
            String msgRetryKey = "msg:retry:" + orderNo;
            Long count = redisTemplate.opsForValue().increment(msgRetryKey);
            // 三次重试
            if (count >= 3) {
                log.error("消息已经到达了重试{}次，请人工排查错误原因：{}", count, e.getMessage());
                // 不能重试
                channel.basicNack(deliveryTag, false, false);
                redisTemplate.delete(msgRetryKey);
            } else {
                log.info("消息重试{}次", count);
                channel.basicNack(deliveryTag, false, true);
            }
        } catch (Exception e) {
            log.error("签收消息时网络出现了故障，异常原因：{}", e.getMessage());
            channel.basicNack(deliveryTag, false, false);
        }

    }
}
